package com.example.simplesvc;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;


//自己创建出来的，不被spring管理 要关闭
public class MyOutOfSpringService implements MyServerStopListener {


    private ExecutorService pool = Executors.newFixedThreadPool(10);

    private Timer mytimer = new Timer();


    private Logger log = LoggerFactory.getLogger(MyOutOfSpringService.class);

    public MyOutOfSpringService() {
        // 本实例 模拟不被spring管理的对象，本身持有 executor，timer对象，这些对象又持有工作线程， 因此需要感知
        // 服务要停止的事件，然后停止 executor和timer对象
        // 注册到注册器，以便接收服务停止事件
        MyServerStopListenerRegister.getInstance().registerListener(this);
    }


    public void runWithExecutor(Runnable runnable) {
        pool.submit(runnable);
    }


    public void runWithTimer(Runnable runnable) {
        mytimer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                runnable.run();
            }
        }, 5000, 5000);
    }

    @Override
    public void onServerStopping() {

        log.info("trying shutdown executor");
        try {
            pool.shutdown(); // Disable new tasks from being submitted
            // try {      // Wait a while for existing tasks to terminate
            if (!pool.awaitTermination(10, TimeUnit.SECONDS)) {
                log.info("executor shutdown now ");
               pool.shutdownNow(); // Cancel currently executing tasks
                // Wait a while for tasks to respond to being cancelled
                if (!pool.awaitTermination(10, TimeUnit.SECONDS)) {
                    log.info("Pool did not terminate");
                }

            }
            log.info("executor stopped");
        } catch (InterruptedException ie) {      // (Re-)Cancel if current thread also interrupted
            log.error("", ie);
            pool.shutdownNow();
            // Preserve interrupt status
            Thread.currentThread().interrupt();
        }


        try {
            mytimer.cancel();
            log.info("timer cancel");
        } catch (Exception e) {
            log.error("", e);
        }
    }
}
